<script lang="ts" setup>
import { getPatientConsultOrderDetailAPI } from '@/apis/consult'
import { useUserStore } from '@/stores/user'
import { OrderStatus, type GetPatientConsultOrderDetailData } from '@/types/consult'
import { io, type Socket } from '@hyoga/uni-socket.io'
import { nextTick, ref } from 'vue'
import RoomStatus from './components/room-status.vue'
import PatientInfo from './components/patient-info.vue'
import NotifyInfo from './components/notify-info.vue'
import MessageInfo from './components/message-info.vue'
import type { ChatMsgListData, MsgItem } from '@/types/room'
import { postUploadAPI } from '@/apis/common'
import PrescriptionInfo from './components/prescription-info.vue'
const props = defineProps<{
  orderId: string
  payResult: string
}>()

// 1. 处理支付失败
if (props.payResult === 'false') {
  uni.switchTab({
    url: '/pages/my/my',
  })
}

// 2. 建立连接
const store = useUserStore()
const socket: Socket = io('https://consult-api.itheima.net', {
  // 传递 token，用于身份认证（后端要求）
  auth: { token: `Bearer ${store.token}` },
  // 传递订单 id，用于查询订单信息（后端要求）
  query: { orderId: props.orderId },
  // 支持 websocket 和 轮询 传输方式（为了更好的兼容性）
  transports: ['websocket', 'polling'],
  // 超时时间
  timeout: 5000,
})
const orderDetail = ref<GetPatientConsultOrderDetailData>()
const getOrderDetail = async () => {
  const res = await getPatientConsultOrderDetailAPI(props.orderId)
  console.log(res)
  orderDetail.value = res.data
}
getOrderDetail()
// 监听订单状态变化，statusChange 为后端定义的事件名称
socket.on('statusChange', () => {
  // 重新获取订单详情，包含订单状态，倒计时秒数
  getOrderDetail()
})
const msgList = ref<MsgItem[]>([])
socket.on('chatMsgList', (res: ChatMsgListData) => {
  if (res.code !== 10000) return
  res.data?.forEach((item) => {
    if (item.items) {
      msgList.value.push(
        {
          msgType: 31,
          createTime: item.createTime,
          msg: {
            content: item.createTime,
          },
        },
        ...item.items
      )
    }
  })
})
socket.on('connect', () => {
  // 建立连接成功
  console.log('连接建立成功')
})

socket.on('error', () => {
  // 错误异常消息
  console.log('出现错误')
})

socket.on('disconnect', () => {
  // 已经断开连接
  console.log('断开连接')
})
socket.on('receiveChatMsg', async (message: MsgItem) => {
  // 修改消息为已读
  socket.emit('updateMsgStatus', message.id)
  // 接收到的消息追加到消息列表中
  msgList.value.push(message)
  await nextTick()
  scrollIntoViewId.value = `id-${message.id}`
})
const textMessage = ref('')
const sendMessage = () => {
  if (textMessage.value.trim() === '') {
    uni.showToast({ title: '请输入内容', icon: 'none' })
    return
  }
  // 发送消息给服务器
  socket.emit('sendChatMsg', {
    from: store.userInfo?.id, // 发送人id
    to: orderDetail.value?.docInfo?.id, // 接收人id (医生id)
    msgType: 1, // 消息类型，1 表示文字消息
    msg: {
      content: textMessage.value, // 文本消息内容
    },
  })
  // 发送消息后，清空输入框
  textMessage.value = ''
}

// 上传图片
const handleUploadImage = async () => {
  // 非咨询中状态，不能发送图片消息
  if (orderDetail.value?.status !== OrderStatus.ZiXunZhong) {
    uni.showToast({ title: '当前状态不能发送图片消息', icon: 'none' })
    return
  }

  // 选择图片（支持相册和相机）
  const { tempFilePaths } = await uni.chooseImage({
    count: 1, // 最多可以选择的图片张数
    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
  })

  // 上传图片，传递图片路径
  const res = await postUploadAPI(tempFilePaths[0])
  console.log(res)
  socket.emit('sendChatMsg', {
    from: store.userInfo?.id, // 发送人id
    to: orderDetail.value?.docInfo?.id, // 接收人id (医生id)
    msgType: 4, // 消息类型，4 表示图片消息
    msg: {
      picture: res.data,
    },
  })
}
const scrollIntoViewId = ref('')
</script>

<template>
  <view class="room-page">
    <!-- 咨询室状态组件 -->
    <RoomStatus
      v-if="orderDetail"
      :status="orderDetail?.status"
      :statusValue="orderDetail?.statusValue"
      :countdown="orderDetail?.countdown!"
    />
    <!-- 消息列表 -->
    <scroll-view
      refresher-enabled
      refresher-background="#f2f2f2"
      scroll-y
      style="flex: 1; overflow: hidden"
      :scroll-into-view="scrollIntoViewId"
    >
      <view class="message-container">
        <!-- 此处将来填充更多代码... -->
        <view v-for="item in msgList" :key="item.id" :id="`id-${item.id}`">
          {{ item.msgType }}
          <PatientInfo v-if="item.msgType === 21" :info="item.msg?.consultRecord" />
          <NotifyInfo v-else-if="item.msgType === 31 || item.msgType === 32" :type="item.msgType">
            {{ item.msg?.content }}
          </NotifyInfo>
          <MessageInfo v-else-if="item.msgType === 1 || item.msgType === 4" :message="item" />
          <!-- 电子处方 -->
          <PrescriptionInfo v-else-if="item.msgType === 22" :info="item.msg?.prescription" />
        </view>
      </view>
    </scroll-view>

    <!-- 发送消息 -->
    <view class="message-bar">
      <template v-if="true">
        <uni-easyinput
          v-model="textMessage"
          @confirm="sendMessage"
          :disabled="orderDetail?.status !== OrderStatus.ZiXunZhong"
          :clearable="false"
          :input-border="false"
          placeholder-style="font-size: 32rpx; color: #c3c3c5;"
          placeholder="问医生"
        />
        <view class="image-button" @click="handleUploadImage">
          <uni-icons size="40" color="#979797" type="image"></uni-icons>
        </view>
      </template>
      <button v-else class="uni-button">咨询其它医生</button>
    </view>
  </view>
</template>

<style lang="scss">
@import './index.scss';
</style>
